package service.impl;

import service.StudentsService;
import service.UserService;
import entity.Students;
import entity.User;
import mapper.StudentsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentsImpl implements StudentsService {

    @Autowired
    private StudentsMapper mapper;

    @Autowired
    private UserService userService;

    @Override
    public Students getById(Integer id) {
        return mapper.selectById(id);
    }

    @Override
    public List<Students> getAll() {
        return mapper.selectAll();
    }

    @Override
    public int create(Students s) {
        // 1. 先创建用户
        User user = new User();
        user.setUsername(s.getStudentId().toString());
        user.setPassword("123456");
        user.setUserType(0);
        user.setCreatedAt(LocalDateTime.now());

        int result = userService.create(user);
        if (result <= 0 || user.getUserId() == null) {
            throw new RuntimeException("用户创建失败");
        }

        // 2. 插入学生信息
        s.setUserId(user.getUserId());
        s.setCreatedAt(LocalDateTime.now());
        return mapper.insert(s);
    }

    @Override
    public int update(Students s) {
        // 先查询现有的学生信息，获取userId
        Students existingStudent = mapper.selectById(s.getStudentId());
        if (existingStudent == null) {
            throw new RuntimeException("学生信息不存在");
        }

        // 保留原有的userId，避免前端需要传递
        s.setUserId(existingStudent.getUserId());
        s.setUpdatedAt(LocalDateTime.now());
        return mapper.update(s);
    }

    @Override
    public int delete(Integer id) {
        return mapper.delete(id);
    }

    @Override
    public Students getByUserId(Integer userId) {
        return mapper.selectByUserId(userId);
    }
}
